package com.graduate.examapp.viewmodel

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.graduate.examapp.entity.ExamTask
import com.graduate.examapp.entity.LoginData
import com.graduate.examapp.model.ExamTaskRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class HomeViewModel : ViewModel() {
    val taskLiveData = MutableLiveData<List<ExamTask>?>()

    val notifyLiveData = MutableLiveData<String>()

    private val examTaskRepository = ExamTaskRepository()
    val logoutLiveData = MutableLiveData<Boolean?>()

    fun fetchTask(id: String) {
        Log.d("HomeViewModel", id)
        val examTaskList = ArrayList<ExamTask>()
        viewModelScope.launch(Dispatchers.IO) {
            val assistResponse = examTaskRepository.fetchAssistExamTask(id)
            //Log.d("HomeViewModel", assistResponse.message)
            val invigilateResponse = examTaskRepository.fetchInvigilateExamTask(id)
            if (assistResponse.code == LoginViewModel.REQUEST_OK && invigilateResponse.code == LoginViewModel.REQUEST_OK) {
                examTaskList.addAll(assistResponse.data)
                examTaskList.addAll(invigilateResponse.data)
            } else {
                //请求失败 显示请求原因
                notifyLiveData.postValue(assistResponse.message)
            }
            Log.d("HomeViewModel", examTaskList.size.toString())
            taskLiveData.postValue(examTaskList)
        }
    }

    fun logout() {
        viewModelScope.launch(Dispatchers.IO) {
            val logoutResponse = examTaskRepository.logout()
            if (logoutResponse.code == LoginViewModel.REQUEST_OK) {
                logoutLiveData.postValue(true)
            }
        }
    }
}